package com.neo.tiny.admin.service.msg.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.neo.tiny.admin.entity.msg.SysMsgNotifyTemplateDO;
import com.neo.tiny.admin.service.msg.NotifySendService;
import com.neo.tiny.admin.service.msg.SysMsgNotifyService;
import com.neo.tiny.admin.service.msg.SysMsgNotifyTemplateService;
import com.neo.tiny.common.enums.CommonStatusEnum;
import com.neo.tiny.common.exception.WebApiException;
import com.neo.tiny.middle.socket.api.SocketSessionClient;
import com.neo.tiny.middle.socket.enums.WebSocketType;
import com.neo.tiny.query.LambdaQueryWrapperBase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description: 站内信收发业务实现类
 * @Author: yqz
 * @CreateDate: 2023/2/11 21:37
 */
@Slf4j
@Service
public class NotifySendServiceImpl implements NotifySendService {


    @Autowired
    private SysMsgNotifyTemplateService notifyTemplateService;

    @Autowired
    private SysMsgNotifyService msgNotifyService;

    @Autowired
    private List<SocketSessionClient<Long>> socketSessionClients;

    @Override
    public Long sendSingleNotify(Long toUserId, Long fromUserId, String templateCode, Map<String, Object> templateParams) {

        SysMsgNotifyTemplateDO template = checkTemplate(templateCode);
        if (CommonStatusEnum.DISABLE.getStatus().equals(template.getStatus())) {
            log.info("该模板：【{}】已关闭,无法给用户：【{}】发送", templateCode, toUserId);
            return null;
        }

        checkParams(template, templateParams);

        String content = StrUtil.format(template.getTemplateContent(), templateParams);
        Long notifyMsgId = msgNotifyService.createNotifyMsg(toUserId, fromUserId, template, content);

        // TODO 发送WebSocket 消息

        SocketSessionClient<Long> socketSessionClient = socketSessionClients
                .stream()
                .filter(client -> client.support(WebSocketType.SYS_ADMIN.getType()))
                .findFirst().get();
        socketSessionClient.sendMsg(toUserId, content);
        return notifyMsgId;
    }


    /**
     * 校验站内信模板
     *
     * @param templateCode 模板编码
     * @return
     */
    public SysMsgNotifyTemplateDO checkTemplate(String templateCode) {

        SysMsgNotifyTemplateDO template = notifyTemplateService.getOne(new LambdaQueryWrapperBase<SysMsgNotifyTemplateDO>()
                .eq(SysMsgNotifyTemplateDO::getTemplateCode, templateCode));

        if (BeanUtil.isEmpty(template)) {
            throw new WebApiException("站内信模板不存在");
        }
        return template;
    }

    public void checkParams(SysMsgNotifyTemplateDO template, Map<String, Object> templateParams) {

        template.getTemplateParams().forEach(key -> {
            Object value = templateParams.get(key);
            if (value == null) {
                throw new WebApiException(StrUtil.format("该模板参数缺失：{}", key));
            }
        });
    }
}
